//
//  LZUploadImagePresenter.m
//  laziz_Consumer
//
//  Created by xbn_iMac on 2016/11/29.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZUploadImagePresenter.h"
#import "UIImage+LZCompression.h"
#import "LZDateFormatterManager.h"

@implementation LZUploadImagePresenter

/**
 上传图片
 
 @param imageFile 图片
 @param businessId 业务ID,如果上传头像就是用户ID
 @param businessType 业务类型，1:头像 2:优惠视频 3:评论图片
 @param businessNo 图片的序号
 @param isThumb 不缩放传NO；缩放传YES
 @param aSize 可为空，默认{200，200}，空时传CGSizeZero
 
 */

+ (id)uploadImage:(UIImage *)imageFile
        andBusinessId:(NSString*)businessId
      andBusinessType:(NSString*)businessType
        andBusinessNo:(NSString*)businessNo
           andIsThumb:(BOOL)isThumb
              andSize:(CGSize)aSize
                 andBlock:(void (^)(id, NSError *))block {
    
    NSData *imageData = [imageFile compressionImageToDataFrameSize:aSize maxFileSize:200];
    
    NSString * urlPath = [NSString stringWithFormat:@"/upload/fileInfo/upload"];
    
    NSMutableDictionary * param_Dict = [NSMutableDictionary dictionary];
    if (businessId) {
        [param_Dict setObject:businessId forKey:@"businessId"];
    }
    if (businessType) {
        [param_Dict setObject:businessType forKey:@"businessType"];
    }
    if (businessNo) {
        [param_Dict setObject:businessNo forKey:@"businessNo"];
    }
    if (isThumb) {
        [param_Dict setObject:@"yes" forKey:@"isThumb"];
    }
    if (!CGSizeEqualToSize(aSize, CGSizeZero)) {
        [param_Dict setObject:[NSNumber numberWithInteger:aSize.width] forKey:@"width"];
        [param_Dict setObject:[NSNumber numberWithInteger:aSize.height] forKey:@"height"];
    }
    
    DLog(@"%@", param_Dict);
    
    UploadRequestConstructingBodyBlock formDataBlock = ^(id<AFMultipartFormData> formData) {
        NSString * name = [[LZDateFormatterManager shareInstance] stringFromCustomFormat:@"yyyyMMddHHmmssSSS" andDate:[NSDate date]];
        NSString * fileName = [NSString stringWithFormat:@"%@.jpg",name];
        [formData appendPartWithFileData:imageData name:@"upLoad" fileName:fileName mimeType:@"image/jpeg"];
    };
    
    UploadRequestSuccessBlock successBlock = ^(NSURLSessionDataTask * __unused task, id rawData) {
        NSMutableDictionary *data = [(NSDictionary *)rawData mutableCopy];
        if (block) block(data, nil);
    };
    
    UploadRequestFailureBlock failureBlock = ^(NSURLSessionDataTask *__unused task, NSError *error) {
        if (block) block(nil, error);
    };
    
    return [[NetworkServiceManager manager] executePostTask:urlPath parameters:param_Dict
                                  constructingBodyWithBlock:formDataBlock
                                                   progress:nil
                                                    success:successBlock
                                                       fail:failureBlock];
    
}

@end
